/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "softbus_session_listener.h"

#include "securec.h"
#include "constants.h"
#include "spatial_awareness_common.h"
#include "spatial_softbus_session.h"

namespace OHOS {
namespace Msdp {
std::shared_ptr<ICommunicateInterface::RemoteListener> SoftbusSessionListener::remoteListener_;

void SoftbusSessionListener::RegisterListoner(
    const std::shared_ptr<ICommunicateInterface::RemoteListener>& remoteListener)
{
    remoteListener_ = std::move(remoteListener);
}

int32_t SoftbusSessionListener::OnSessionOpened(int32_t sessionId, int32_t result)
{
    SPATIAL_LOGI(MODULE_SERVICE,
        "SoftbusSessionListener.OnSessionOpened, sessionId %{public}d, result %{public}d", sessionId, result);

    remoteListener_->OnSessionOpened(sessionId, result);
    return SPATIALMANAGER_OK;
}

void SoftbusSessionListener::OnSessionClosed(int32_t sessionId)
{
    SPATIAL_LOGI(MODULE_SERVICE, "SoftbusSessionListener.OnSessionClosed, sessionId:%{public}d", sessionId);
    remoteListener_->OnSessionClosed(sessionId);
}

void SoftbusSessionListener::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen)
{
    SPATIAL_LOGI(MODULE_SERVICE,
        "SoftbusSessionListener.OnBytesReceived, sessionId:%{public}d, dataLen:%{public}d", sessionId, dataLen);
    if (sessionId < 0 || data == nullptr || dataLen <= 0) {
        SPATIAL_LOGE(MODULE_SERVICE, "OnBytesReceived param check failed");
        return;
    }

    remoteListener_->OnBytesReceived(sessionId, data, dataLen);
    SPATIAL_LOGI(MODULE_SERVICE, "OnBytesReceived completed");
    return;
}

void SoftbusSessionListener::OnMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen)
{
    SPATIAL_LOGI(MODULE_SERVICE,
        "SoftbusSessionListener.OnMessageReceived, sessionId:%{public}d, dataLen:%{public}d", sessionId, dataLen);
    int time = 1000;
    if (sessionId < 0 || data == nullptr || dataLen <= 0) {
        SPATIAL_LOGE(MODULE_SERVICE, "OnMessageReceived param check failed");
        return;
    }

    std::thread messageReceivedThread(&ICommunicateInterface::RemoteListener::OnMessageReceived, remoteListener_,
        sessionId, data, dataLen);
    messageReceivedThread.join();
    std::this_thread::sleep_for(std::chrono::milliseconds(time));
    SPATIAL_LOGI(MODULE_SERVICE, "OnMessageReceived completed");
}
} // namespace Msdp
} // namespace OHOS